package com.itbaiyun.jcinterface.controller;

import com.itbaiyun.common.model.common.ResultUtils;
import com.itbaiyun.common.model.type.LovelornSentence;


import com.itbaiyun.common.model.type.WeatherInfo;
import com.itbaiyun.common.model.type.param.WeatherParam;
import com.itbaiyun.jcinterface.service.LovelornSentenceService;
import com.itbaiyun.jcinterface.service.WeatherService;
import com.itbaiyun.project.common.BaseResponse;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;

@Slf4j
@RestController
@RequestMapping("/common")
public class APIController {

    @Resource
    private LovelornSentenceService lovelornSentenceService;
    @Resource
    private WeatherService weatherService;

    /**
     * 随机失恋文案API
     * @return
     */
    @GetMapping("/lovelorn")
//    @Operation(summary = "随机失恋文案API")
    public BaseResponse<LovelornSentence> getRandomLovelornSentence() {
        Long id = lovelornSentenceService.randomId();
        return ResultUtils.success(lovelornSentenceService.getSentenceById(id));
    }

    /**
     * 天气查询API
     * @param weatherParam
     * @param request
     * @return
     */
    @GetMapping("/weather")
    public BaseResponse<WeatherInfo> nowWeather( String weatherParam, HttpServletRequest request) {
        String body = request.getHeader("body");
        if (body != null) {
            try {
                // 假设客户端使用 UTF-8 编码
                body = new String(body.getBytes("ISO-8859-1"), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.error("解码错误", e);
            }
        }
        if (StringUtils.isEmpty(body)) {
            return weatherService.getWeatherByRequest(request);
        }
        return weatherService.getWeatherByCityName(body);
    }

}
